#!/bin/bash

ACTION=${1:-on}
SWAP_SIZE=${2:-2G}
SWAP_FILE="/swapfile"

enable_swap() {
    if swapon --show | grep -q "$SWAP_FILE"; then
        echo "Swap 文件 $SWAP_FILE 已启用，跳过操作。"
        exit 0
    fi

    if swapon --show | grep -q "^"; then
        echo "系统已启用其他 swap，跳过创建。"
        exit 0
    fi

    if [ -f "$SWAP_FILE" ]; then
        echo "Swap 文件已存在但未启用，正在启用..."
        chmod 600 "$SWAP_FILE"
        mkswap "$SWAP_FILE"
        swapon "$SWAP_FILE"
        grep -q "$SWAP_FILE" /etc/fstab || echo "$SWAP_FILE none swap sw 0 0" | tee -a /etc/fstab
        echo "Swap 文件启用成功。"
        exit 0
    fi

    echo "创建 ${SWAP_SIZE} 的 swap 文件..."
    fallocate -l "$SWAP_SIZE" "$SWAP_FILE"
    chmod 600 "$SWAP_FILE"
    mkswap "$SWAP_FILE"
    swapon "$SWAP_FILE"
    echo "$SWAP_FILE none swap sw 0 0" | tee -a /etc/fstab
    echo "Swap 文件创建并启用成功。"
}

disable_swap() {
    if swapon --show | grep -q "$SWAP_FILE"; then
        echo "正在禁用 swap..."
        swapoff "$SWAP_FILE"
    else
        echo "Swap 文件未启用，跳过 swapoff。"
    fi

    if grep -q "$SWAP_FILE" /etc/fstab; then
        echo "从 /etc/fstab 中移除 swap 配置..."
        sed -i "\|$SWAP_FILE|d" /etc/fstab
    fi

    if [ -f "$SWAP_FILE" ]; then
        echo "删除 swap 文件..."
        rm -f "$SWAP_FILE"
    fi

    echo "Swap 文件已禁用并删除。"
}

if [ "$ACTION" = "on" ]; then
    enable_swap
elif [ "$ACTION" = "off" ]; then
    disable_swap
else
    echo "无效参数：$ACTION"
    echo "用法: sudo bash $0 [on|off] [大小]"
    exit 1
fi
